package xdu.lz.stage1_basic.chapter1_threadsafe.synchronize;

class SynchronizedLock{

    public synchronized void m1(){
        System.out.println("m1 start");
        System.out.println("current thread:"+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    public synchronized void m2(){
        System.out.println("m2 start");
        System.out.println("current thread:"+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public void m3(){
        System.out.println("m3 start");
        System.out.println("current thread:"+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class SynchronizedTest {
    public static void main(String[] args) {
        //测试1：非静态方法加synchronized锁住的是当前对象的实例this
        SynchronizedLock synLock1 = new SynchronizedLock();
        SynchronizedLock synLock2 = new SynchronizedLock();
        SynchronizedLock synLock3 = new SynchronizedLock();
        //由于三个对象实例this不同，所以这三个会同时输出
        new Thread(()->{
            synLock1.m1();
        },"t1").start();
        new Thread(()->{
            synLock2.m2();
        },"t2").start();
        new Thread(()->{
            synLock3.m3();
        },"t3").start();
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("===============");
        //测试：使用同一个对象this
        SynchronizedLock synLock = new SynchronizedLock();
        //m1和m2用的是同一个this对象，所以只有一个会先被执行，另一个被锁住
        new Thread(()->{
            synLock.m1();
        },"t1").start();
        new Thread(()->{
            synLock.m2();
        },"t2").start();
        new Thread(()->{
            synLock.m3();
        },"t3").start();
    }
}
